package com.iweb.myfilter;

import org.apache.log4j.Logger;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;


/**
 * 自定义过滤器1
 * 拦截规则  所有请求都拦截
 */
@WebFilter(filterName = "Filter3",urlPatterns = {"/admin/*"})
public class Filter3 implements Filter {
    private final static Logger logger = Logger.getLogger(Filter3.class);


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        logger.debug("过滤器3初始化了");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        logger.debug("过滤器3开始拦截");
        String path = servletRequest.getServletContext().getContextPath();
        HttpSession httpSession = ((HttpServletRequest) servletRequest).getSession();
        if (httpSession.getAttribute("loginUser")==null){
            ((HttpServletResponse) servletResponse).sendRedirect(path+"/login.jsp");
        }else{
            //放行
            filterChain.doFilter(servletRequest,servletResponse);
        }
        //当有多个执行
        logger.debug("过滤器3执行之后。。。。");
    }
    @Override
    public void destroy() {
        logger.debug("过滤器3销毁了");
    }
}